package com.tp;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.devsmart.android.ui.HorizontalListView;

public class Object extends CustomWindow implements OnClickListener {
	int id_Obj;
	String pathPhoto;
	String url;
	private String[] r;
	String comment[];
	ListView comment_txt;
	int type;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.listviewdemo);

		this.title.setText("Thông tin đối tượng");
		TextView name = (TextView) findViewById(R.id.obj_name_txt);
		TextView addr = (TextView) findViewById(R.id.obj_addr_txt);
		TextView phone = (TextView) findViewById(R.id.obj_phone_txt);
		Button view_cmt = (Button) findViewById(R.id.view_cmt);
		view_cmt.setOnClickListener(this);
		comment_txt = (ListView) findViewById(R.id.comment);

		// String url = ListObject.obj.getString("");

		try {
			name.setText(ListObject.obj.getString("name"));
			addr.setText("Địa chỉ " + ListObject.obj.getString("address"));
			if (!ListObject.obj.getString("phone").equals("null")) {
				phone.setText("Số điện thoại "
						+ ListObject.obj.getString("phone"));
			}
			id_Obj = ListObject.obj.getInt("id_Obj");
			type = ListObject.obj.getInt("id_Type");
			if (type == 1)
				this.icon.setImageResource(R.drawable.hotel);
			else if (type == 2)
				this.icon.setImageResource(R.drawable.restaurant);
			else if (type == 3)
				this.icon.setImageResource(R.drawable.picnic);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		r = getPath();
		HorizontalListView listview = (HorizontalListView) findViewById(R.id.listview);
		listview.setAdapter(mAdapter);

	}

	private BaseAdapter mAdapter = new BaseAdapter() {

		private OnClickListener mOnButtonClicked = new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * AlertDialog.Builder builder = new
				 * AlertDialog.Builder(HorizontalListViewDemo.this);
				 * builder.setMessage("hello from " + v);
				 * builder.setPositiveButton("Cool", null); builder.show();
				 */

			}
		};

		@Override
		public int getCount() {
			// return dataObjects.length;
			return r.length;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View retval = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.viewitem, null);
			// TextView title = (TextView) retval.findViewById(R.id.title);
			/*
			 * Button button = (Button) retval.findViewById(R.id.clickbutton);
			 * button.setOnClickListener(mOnButtonClicked);
			 */
			// title.setText(dataObjects[position]);
			/*
			 * ExifInterface exif; int rotate = 0; try { exif = new
			 * ExifInterface(DialogCustomize.fileName);
			 * 
			 * int orientation = exif.getAttributeInt(
			 * ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			 * 
			 * switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_270:
			 * rotate = 270;
			 * 
			 * break; case ExifInterface.ORIENTATION_ROTATE_180: rotate = 0;
			 * 
			 * break; case ExifInterface.ORIENTATION_ROTATE_90: rotate = 90;
			 * 
			 * break; } } catch (IOException e) { // TODO Auto-generated catch
			 * block e.printStackTrace(); }
			 * 
			 * Matrix matrix = new Matrix(); matrix.postRotate(rotate);
			 */
			Bitmap bimage = null;
			try {

				bimage = getBitmapFromURL(Constant.path_photo + r[position]);
				bimage = Bitmap.createScaledBitmap(bimage, 150, 150, true);

				ImageView image = (ImageView) retval.findViewById(R.id.image);
				image.setImageBitmap(bimage);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return retval;
		}

	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.view_cmt:
			comment = getComment();

			if (comment != null) {
				ListAdapter adapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_list_item_1, comment);
				comment_txt.setAdapter(adapter);
				comment_txt.setScrollbarFadingEnabled(true);
			} else
				Toast.makeText(this, "Không có bình luận nào",
						Toast.LENGTH_SHORT).show();

			break;

		}

	}

	private String[] getComment() {
		// TODO Auto-generated method stub
		String comment[] = null;
		JSONArray jArray = null;
		JSONObject json_data = null;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Obj", "" + id_Obj));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/CommentController/getComment", postParameters);

			if (result != null) {

				jArray = new JSONArray(result);
				comment = new String[jArray.length()];
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					int id_User = json_data.getInt("id_User");
					comment[i] = getUserName(id_User) + " : "
							+ json_data.getString("content");

				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return comment;
	}

	private String getUserName(int id_User) {
		// TODO Auto-generated method stub
		String username = null;
		JSONArray jArray = null;
		JSONObject json_data = null;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_User", "" + id_User));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/UserController/getUserName", postParameters);

			if (result != null) {

				jArray = new JSONArray(result);
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					username = json_data.getString("username");

				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return username;
	}

	public static Bitmap getBitmapFromURL(String src) {
		try {
			Log.e("src", src);
			URL url = new URL(src);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			Bitmap myBitmap = BitmapFactory.decodeStream(input);
			Log.e("Bitmap", "returned");
			return myBitmap;
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("Exception", e.getMessage());
			return null;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_object, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		Intent i;
		switch (item.getItemId()) {
		case R.id.obj_findway:

			Intent intent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("http://maps.google.com/maps?"
							+ "saddr=latitude,longitude" + "&daddr="
							+ ListObject.latitude + "," + ListObject.longitude));
			intent.setClassName("com.google.android.apps.maps",
					"com.google.android.maps.MapsActivity");

			startActivity(intent);
			break;
		case R.id.obj_detail:
			/*
			 * i = new Intent(this, Detail.class); startActivity(i);
			 */
			try {
				url = ListObject.obj.getString("url");
				if (!url.equals("")) {
					Uri uri = Uri.parse(url);
					Intent j = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(j);
				} else {
					Toast.makeText(this, "Không có thông tin chi tiết",
							Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {

			}

			break;
		}
		return false;

		// return false;
	}

	public String[] getPath() {
		String r[] = {};
		JSONArray jArray = null;
		JSONObject json_data = null;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Obj", "" + id_Obj));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/PhotoController/getPhoto", postParameters);
			jArray = new JSONArray(result);
			r = new String[jArray.length()];
			int i;
			for (i = 0; i < jArray.length(); i++) {
			
					json_data = jArray.getJSONObject(i);
					r[i] = json_data.getString("path");
				}
				// Log.d("A", json_data.getString("name"));

				// TODO Auto-generated catch block


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// return r;
		return r;
	}

}
